//
//  SRMainViewController.m
//  SportRing
//
//  Created by mykoma on 14-4-3.
//  Copyright (c) 2014年 HotOne. All rights reserved.
//

#import "SRMainViewController.h"
#import "SRMainView.h"
#import "SRSelectDateView.h"
#import "SRSetTargetView.h"
#import "SRSportShareViewController.h"
#import "SRSportDetailViewController.h"
#import "SRManager.h"
#import "SRTaskService.h"
#import "SRDB.h"
#import "SRSportBleService.h"
#import "SRSportNetService.h"
#import "NSDate+Additionals.h"
#import "SRSportDetailTableViewCell.h"
#import "NSDate+Additionals.h"
#import "SRSportTask+Cate.h"

@interface SRMainViewController ()

@property (nonatomic, weak) IBOutlet SRMainView * srMainView;

@property (nonatomic, weak) IBOutlet SRSelectDateView * srSelectDateView;

@property (nonatomic, strong)SRSleepingViewModel *sleepViewModel;

@property (nonatomic, strong)SRSportViewModel *sportViewModel;

@property (nonatomic, strong)SRDay *srday;

@property (nonatomic, strong) NSTimer * timer;

@end

@implementation SRMainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self addRightImageButton:@"share_icon"];
    
    _srSelectDateView.dateType = SELECTE_DATE_TYPE_MONTH_DAY;
    
    _srMainView.type = MAIN_VIEW_TYPE_SPORT;

    
    @weakify(self);
    [[NSNotificationCenter defaultCenter] addObserverForName:NEW_CURRENT_TASK_DATA_NOTIFY
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification *note)
     {
         if (_srMainView.type == MAIN_VIEW_TYPE_SPORT) {
             [self_weak_ getDayDataByDate:_srSelectDateView.selectedDate];
         }
     }];
    [[NSNotificationCenter defaultCenter] addObserverForName:NEW_CURRENT_SPORT_DATA_NOTIFY
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification *note)
     {
         if (_srMainView.type == MAIN_VIEW_TYPE_SPORT) {
             [self_weak_ getDayDataByDate:_srSelectDateView.selectedDate];
         }
     }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:NEW_SLEEP_DATA_NOTIFY
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification *note)
     {
         if (_srMainView.type == MAIN_VIEW_TYPE_SLEEPING) {
             [self_weak_ getDayDataByDate:_srSelectDateView.selectedDate];
         }
     }];
    
    [self switchType:_srMainView.type];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [_srMainView refreshData];
}

//从数据库获取天数据
- (void)getDayDataByDate:(NSDate *)date
{
    SRSportTask * task = [SRSportTask findTaskCINEForDay:[date formattedBy_yyyyMMdd]];
    
    CGFloat process = 0;
    if (task.totalCounter.integerValue != 0) {
        process = task.completedCounter.floatValue / task.totalCounter.floatValue;
    }
    process = process > 1.0 ? 1.0 : process;
    SRAimSportViewModel *aimModel = [[SRAimSportViewModel alloc] initWithAimDistance:task.totalCounter.intValue
                                                                        chartProcess:process];
    
    if ([date isToday])
    {
        SRCurrentData * currentData = [SRCurrentData findCurrentDataForMe:[SRMe currentUser]];
        
        int steps = currentData.walkCounter.intValue + currentData.runCounter.intValue + currentData.upstairCounter.intValue;
        _sportViewModel = [[SRSportViewModel alloc] initWithSteps:steps
                                                          calorie:currentData.calori.intValue
                                                         distance:currentData.distance.floatValue / 5000000
                                                         aimModel:aimModel];
    }
    else
    {
        SRDay * day = [SRDay findDayCINEForDate:date forMe:[SRMe currentUser]];
        _sportViewModel = [[SRSportViewModel alloc] initWithSteps:[day countOfSteps]
                                                          calorie:[day countOfCalorie]
                                                         distance:[day countOfDistance] / 5000000
                                                         aimModel:aimModel];
    }
    
    SRDay * day = [SRDay findDayForDate:date forMe:[SRMe currentUser]];
    _srday = day;
    
    self.sleepViewModel = [[SRSleepingViewModel alloc] initWithDeepTime:[SRSleep minutesOfDeepSleepForDay:day]
                                                             simpleTime:[SRSleep minutesOfLightSleepForDay:day]
                                                             activeTime:[SRSleep minutesOfActiveSleepForDay:day]
                                                        sleepingQuality:[SRSleep sleepLevelForDay:day]
                                                            sleepingTip:@""];
    
    [_srMainView setMainViewDataWithSRSportViewModel:_sportViewModel withSRSleepingViewModel:_sleepViewModel type:_srMainView.type];
}

- (void)getSportDataForDay:(NSDate *)date type:(MAIN_VIEW_TYPE)type
{
    NSString *dayStr = [NSDate stringFromDate:date format:@"yyyy-MM-dd"];
    [SVProgressHUD show];
    
    if (type == MAIN_VIEW_TYPE_SPORT)
    {
        [[[SRSportNetService getTaskByDay:dayStr] flattenMap:^RACStream *(id value) {
            return [SRSportNetService getDaySportWithDate:dayStr];
        }] subscribeNext:^(id x) {
            [SVProgressHUD dismiss];
            
            [self getDayDataByDate:_srSelectDateView.selectedDate];
        } error:^(NSError *error) {
            
            [SVProgressHUD showErrorWithStatus:@"获取数据失败"];
        }];
    }
    else
    {
        [[SRSportNetService getSleepForDay:dayStr] subscribeNext:^(id x) {
            [SVProgressHUD dismiss];
            
            [self getDayDataByDate:_srSelectDateView.selectedDate];
        } error:^(NSError *error) {
            
            [SVProgressHUD showErrorWithStatus:@"获取数据失败"];
        }];
    }
}

- (void)controlBackTodayButtonShowByDate:(NSDate *)date
{
    if ([date isToday])
    {
        [_srMainView hideBackTodayButton];
    }
    else
    {
        [_srMainView showBackTodayButton];
    }
}

-(void)onRightButtonPressed
{
    UIStoryboard *SportRingMainBoard = [UIStoryboard storyboardWithName:[SRSourceConfig uiMainStoryBoard] bundle:nil];
    
    SRSportShareViewController *next = [SportRingMainBoard instantiateViewControllerWithIdentifier:[SRSourceConfig uiShareInterface]];
    
    next.date = _srSelectDateView.selectedDate;
    
    if (_srMainView.type == MAIN_VIEW_TYPE_SPORT)
    {
        next.shareType = SR_SHARE_TYPE_DAY_SPORT;
        
        SRSportShareContentForDayViewModel *model = [[SRSportShareContentForDayViewModel alloc] init];
        model.steps = _sportViewModel.steps;
        model.distance = _sportViewModel.distance;
        model.kalorie = _sportViewModel.calorie;
        model.completeTask = [_srday.task isCompleted];
        CGFloat encourage = _sportViewModel.calorie / 181;
        model.encourage = encourage;
        
        next.dayShareData = model;

    }
    
    if ((_srMainView.type == MAIN_VIEW_TYPE_SLEEPING))
    {
        next.shareType = SR_SHARE_TYPE_DAY_SLEEPING;
        
        SRSleepingShareContentViewModel *model = [[SRSleepingShareContentViewModel alloc] init];
        
        model.sleepTime = _sleepViewModel.deepSleepingTime + _sleepViewModel.simpleSleepingTime;
        model.turnBodyTime = _sleepViewModel.activeTime;
        model.sleepQuality = _sleepViewModel.sleepingQuality;
        
        next.sleepingShareData = model;

    }
    
    [self.navigationController pushViewController:next animated:YES];
}

#pragma mark - SRMainViewDelegate

-(void)backToday:(SRMainView *)mainView
{
    [_srSelectDateView today];

    [self switchType:mainView.type];
}

-(void)switchType:(MAIN_VIEW_TYPE)type
{
    [self controlBackTodayButtonShowByDate:_srSelectDateView.selectedDate];
    
    //如果是今天，从数据库读取今天的数据
    if ([_srSelectDateView.selectedDate isToday])
    {
        [self getDayDataByDate:_srSelectDateView.selectedDate];
    }
    //如果不是今天，从服务器拉取数据到本地数据库，再读取数据
    else
    {
        [self getSportDataForDay:_srSelectDateView.selectedDate type:type];
    }
}

-(void)srMainSportDetail:(SRMainView *)mainView
{
    UIStoryboard *SportRingMainBoard = [UIStoryboard storyboardWithName:[SRSourceConfig uiMainStoryBoard] bundle:nil];
    
    SRSportDetailViewController *next = [SportRingMainBoard instantiateViewControllerWithIdentifier:@"SRSportDetailViewController"];

    next.date = _srSelectDateView.selectedDate;
    
    [self.navigationController pushViewController:next animated:YES];
}

-(void)settingTarget:(SRMainView *)mainView targetView:(SRSetTargetView *)targetView
{
    SRCurrentTask * task = [SRCurrentTask findCurrentTaskCINEForMe:[SRMe currentUser]];
    [task configAttributesWithBlock:^(SRCurrentTask *aSelf) {
        aSelf.target = @(targetView.setTargetViewModel.steps);
    }];
    
    [SRTaskService updateTaskToDevie:task];
}

- (void)updateData
{
    [self.timer invalidate];
    self.timer = nil;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:60
                                                  target:self
                                                selector:@selector(blueTimeout)
                                                userInfo:nil
                                                 repeats:NO];
    @weakify(self);
    [[[[SRSportBleService readCurrentTaskData] flattenMap:^RACStream *(id value) {
        return [SRSportBleService readCurrentSportData];
    }] flattenMap:^RACStream *(id value) {
        return [SRSportBleService readSleepData];
    }] subscribeNext:^(id x) {
        [_srMainView stopAnimating];
        [self_weak_.timer invalidate];
        self_weak_.timer = nil;
    }];
}

- (void)blueTimeout
{
    [_srMainView stopAnimating];
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - SRSelectDateViewDelegate

- (void)selectedDate:(SRSelectDateView *)srSelectDateView
{
    [self switchType:_srMainView.type];
}


@end
